﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace DAO
{
    class DataProvider
    {
        public static SqlConnection _con;
        static DataProvider()
        {
           
            string connect = @"Data Source=DESKTOP-NBJO5FI\TAI8292;Initial Catalog=CoffeManagement;Integrated Security=True;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            _con = new SqlConnection(connect);
            _con.Open();
        }

        public int ExecuteNonQuery(SqlCommand cmd)
        {
            try
            {
                cmd.Connection = _con;
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }
            return (int)cmd.Parameters["@tontai"].Value;
        }

        public void ExecuteNonQuery1(SqlCommand cmd)
        {
            try
            {
                cmd.Connection = _con;
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }
        }

        public DataTable ExecuteQuery(string sql)
        {
            DataTable dt = new DataTable();
            try
            {
                //cmd.Connection = _con;
                SqlDataAdapter da = new SqlDataAdapter(sql, _con);
                //da.SelectCommand = cmd;
                da.Fill(dt);
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }
            return dt;
        }

        public DataTable ExecuteQuery(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            try
            {
                cmd.Connection = _con;
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(dt);
            }
            catch (Exception ex)
            {
                throw new Exception("Loi khi thuc thi lenh SQL: " + ex.Message);
            }
            finally
            {
                _con.Close();
            }
            return dt;
        }

    }
}
